<?php
$resultMessage = "";

if(isset($_GET["base"])){
    $cpfBase = $_GET["base"];
    $length = strlen($cpfBase);

    for($i=0; $i< (9 - $length); $i++){
        $cpfBase = "0" . $cpfBase;
    }

    $primeiro = $cpfBase[0]*10 + $cpfBase[1]*9 + $cpfBase[2]*8 + $cpfBase[3]*7 + $cpfBase[4]*6 + $cpfBase[5]*5 + $cpfBase[6]*4 + $cpfBase[7]*3 + $cpfBase[8]*2;
    $primeiro = $primeiro%11;
    if($primeiro < 2){
        $primeiro = 0;
    }
    else {
        $primeiro = 11 - $primeiro;
    }

    $cpfBase .= $primeiro;
    $segundo = $cpfBase[0]*11 + $cpfBase[1]*10 + $cpfBase[2]*9 + $cpfBase[3]*8 + $cpfBase[4]*7 + $cpfBase[5]*6 + $cpfBase[6]*5 + $cpfBase[7]*4 + $cpfBase[8]*3 + $cpfBase[9]*2;
    $segundo = $segundo%11;
    if($segundo < 2){
        $segundo = 0;
    }
    else {
        $segundo = 11 - $segundo;
    }

    $resultMessage = "CPF gerado: " . $cpfBase . $segundo;
}

?>

<script language="javascript" type="text/javascript">
function limitText(limitField, limitCount, limitNum) {
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    }
    else {
        limitCount.value = limitNum - limitField.value.length;                                    }
    }
</script>

<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
    <form action="gerador_cpf.php" method="get">
        <label for="base">CPF base: </label>
        <input type="text" name="base" onKeyDown="limitText(this.form.limitedtextarea,this.form.countdown,7);" onKeyUp="limitText(this.form.limitedtextarea,this.form.countdown,7);" maxlength="7">
        <br>
        <input type="submit" value="gerar digitos">
    </form>
    <br>
<?php echo $resultMessage ?>
</body>
